package com.bs.rss.rss;

import java.util.Date;
import java.util.List;

import com.bs.rss.common.enums.EnumPagine;
import com.bs.rss.common.model.data.Channel;
import com.bs.rss.common.model.data.Rss;
import com.bs.rss.common.model.data.User;
import com.bs.rss.common.utils.JsonReturn;
import com.bs.rss.common.utils.RSSLibJMain;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class RssController extends Controller {

	public void channels() {

		Record r = new Record();
		r.set("title", getPara("title", null));
		r.set("channel_id", getParaToInt("channel_id", null));
		r.set("author", getPara("author", null));
		String date = getPara("pubdate", null);
		r.set("pubdate", date);

		Page<Channel> l = Channel.dao.findallrss(getParaToInt("pageIndex", 1), getParaToInt("pageSize", 10), r);
		Ret ret = Ret.create("list", l).set("code", 0).set("count", l.getTotalRow());

		renderJson(ret);

	}

	public void mychannels() {
		User u = getSessionAttr("currentuser");
		Record r = new Record();
		r.set("title", getPara("title", null));
		r.set("channel_id", getParaToInt("channel_id", null));
		r.set("author", u.getLoginname());
		String date = getPara("pubdate", null);
		r.set("pubdate", date);

		Page<Channel> l = Channel.dao.findmyallrss(getParaToInt("pageIndex", 1), getParaToInt("pageSize", 10), r);
		Ret ret = Ret.create("list", l).set("code", 0).set("count", l.getTotalRow());

		renderJson(ret);
	}

	public void add() {
		User u = getSessionAttr("currentuser");
		boolean f = false;
		Ret t = JsonReturn.re.saveFail(EnumPagine.subfail);

		Rss s = getModel(Rss.class, "");

		s.setPubdate(new Date());
		s.setAuthor(u.getLoginname());

		f = s.save();

		if (f) {
			t = JsonReturn.re.saveOk(EnumPagine.ok, s);
		}

		renderJson(t);

	}

	public void del() {
		boolean f = false;
		Ret t = JsonReturn.re.saveFail(EnumPagine.subfail);
		Integer id = getParaToInt("id", 0);

		Rss s = Rss.dao.findById(id);
		f = s.delete();
		if (f) {
			t = JsonReturn.re.saveOk(EnumPagine.ok, s);
		}

		renderJson(t);

	}

	public void datatorss() {

		String s = getPara("url", "");

		int id = getParaToInt("channel", 0);

		List<Rss> lr = null;
		try {
			lr = RSSLibJMain.dao.getAllRssItemBeanList(s, id);
			for (Rss r : lr) {

				r.save();

			}
			renderJson(Ret.ok());

		} catch (Exception e) {
			renderJson(Ret.fail("msg", e.getMessage()));
			e.printStackTrace();
		}

	}

	public void descript() {
		Rss s = Rss.dao.findById(getParaToInt());

		renderHtml(s.getDescription());
	}

}
